package protocol.data.util;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;

import protocol.common.util.CJLog;
import protocol.common.util.ConfigLoader;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;

public class SqlMapKit {
	private static Log logger = CJLog.getLogConsole();
	private static Map<String, SqlMapClient> sqlMapClient = new HashMap<String, SqlMapClient>();
	private static String defaultKey;
	
	public static void init(){
		String fileNames = ConfigLoader.getStr("Ibatis.Pool");
		String[] poolKeys = fileNames.split(",");
		for(String s : poolKeys){
			String fileName = ConfigLoader.getStr("Ibatis."+s+".FileName");
			Reader reader = null;
			try {
				reader = Resources.getResourceAsReader(fileName);
				SqlMapClient client = SqlMapClientBuilder.buildSqlMapClient(reader);
				if(client!=null){
					SqlMapKit.add(s, client);
					logger.info("<系统信息> 加载"+s+":"+fileName+"数据库配置成功");
				}else{
					logger.error("<系统信息> 加载"+s+":"+fileName+"数据库配置失败");
				}
			} catch (IOException e) {
				logger.error("<系统信息> 无法找到名为"+fileName+"的Ibatis配置文件，请检查");
				e.printStackTrace();
			} finally{
				try {
					reader.close();
				} catch (Exception e) {}
			}
		}
 		if(poolKeys.length>0) SqlMapKit.setDefaultKey(poolKeys[0]);
	}
	
	public static void clear(){
		SqlMapKit.sqlMapClient.clear();
		SqlMapKit.sqlMapClient = null;
	}

	public static void setDefaultKey(String key) {
		SqlMapKit.defaultKey = key;
	}

	public static void add(String key, SqlMapClient value) {
		SqlMapKit.sqlMapClient.put(key, value);
	}

	public static Map<String, SqlMapClient> getSqlMapClients() {
		return SqlMapKit.sqlMapClient;
	}

	public static SqlMapClient getSqlMapClient(String clientKey) {
		if(clientKey.equals("DEFAULT")){
			return SqlMapKit.sqlMapClient.get(defaultKey);
		}else{
			return SqlMapKit.sqlMapClient.get(clientKey);
		}
	}

	public static SqlMapClient getSqlMapClient() {
		return SqlMapKit.sqlMapClient.get(defaultKey);
	}
}
